'use strict'

define(function (require, exports, module) {
    var angular = require('angular');
    var dialog = require('@yunke/art-dialog').default;
    require("../../../plugins/select2/select2");
    var util = require('@yunke/core/util').default;
    var api_prefix = G_CONFIG["api_prefix"]; //api前缀
    require('../contract-common');
    var myMath = require('../../common/my-math')

    var ContractReceivableRefund = angular.module('ContractReceivableRefund', ['ContractCommonService']);

    ContractReceivableRefund.filter('signOrIncomeAmount',function(){
            return function(contract){
                //云客签约-直属区域/云客签约-联营区域
                //使用签约金额
                var limitContractArr = ['7f83719a-fce8-11e4-bed8-00155d02c832','7f8422d0-fce8-11e4-bed8-00155d02c832'];
                if(contract.contract_property_id == limitContractArr[0] || contract.contract_property_id == limitContractArr[1]){
                    return contract.sign_amount;
                }else{
                    return contract.income_amount ? contract.income_amount : 0;
                }
            }
        })
        .filter('sumPaymentAmount',function(){
            return function(paymentes){
                var amount = 0;
                if(paymentes){
                    $.each(paymentes, function (i, d) {
                        if (d.__type == 'delete') {
                            return;
                        }
                        amount = myMath.add(amount, d.payment_amount);
                    });
                }
                return amount;
            }

        })
        .filter('remainPaymentAmount', function () {
            return function (paymentes, contract) {
                var amount = 0;
                if(paymentes){
                    $.each(paymentes, function (i, d) {
                        if (d['__type'] == 'delete') {
                            return;
                        }
                        amount = myMath.add(amount, parseFloat(d.payment_amount));
                    });
                }

                var limitContractArr = ['7f83719a-fce8-11e4-bed8-00155d02c832','7f8422d0-fce8-11e4-bed8-00155d02c832'];
                if(contract.contract_property_id == limitContractArr[0] || contract.contract_property_id == limitContractArr[1]){
                    return myMath.sub(contract.sign_amount, amount);
                }else{
                    return myMath.sub(contract.income_amount, amount);
                }

                return 0;
            }
        })
        .service('receivableRefundService', ['$rootScope','$filter', 'contractCommonService', function ($rootScope,$filter, contractCommonService) {
        $rootScope.refundInfo = {};
        $rootScope.editInvoices = [];
        var service = {
            onRefundEditShow: function ($data, $dialog, $dialogScope, refundType, oldRefund, contract, payments) {
                /**
                 * 打开回款编辑界面时初始化
                 * refundType: 1:新增回款，2：修改回款
                 * oldRefund: 原回款
                 * contract : 合同基本信息
                 * payments : 已录入回款信息
                 */
                function edit(){
                    //实收金额变更时，重新计算分摊金额
                    $dialogScope.shareAmount = function(){
                        var items = $dialogScope.editInvoicePayments || [];
                        var refundAmount = ($dialogScope.info.payment_amount || 0);
                        $.each(items, function (i, d) {
                            if (!d._checked || refundAmount <= 0) {
                                d.cur_payment_amount = 0;
                                return true;
                            }
                            d.cur_payment_amount = myMath.sub(d.cur_billing_amount, d.total_payment);
                            refundAmount -= d.cur_payment_amount;
                            if (refundAmount < 0) {
                                d.cur_payment_amount += refundAmount;
                            }
                        });
                    };
                    //默认信息展示
                    contractCommonService.getDisabledInvoice($dialogScope.data.paymentId, function ( msg ) {
                        msg.input_date = msg.input_date || msg.payment_date;
                        $dialogScope.info = msg;
                        $dialogScope.$applyAsync();
                    });
                    //非查看模式取发票信息
                    contractCommonService.getInvoiceReceivableInfoByContract($data, function (json) {
                        $dialogScope.editInvoicePayments = json;
                        $dialogScope.$applyAsync();
                    });
                }

                if( refundType == 2 ){
                    return edit();
                }

                var self = this;
                $dialogScope.maxPayment = $filter('remainPaymentAmount')(payments,contract);
                $dialogScope.onRefundImportNoInvoiceShow = self.onRefundImportNoInvoiceShow;

                $dialogScope.importPayment = function (item) {
                    if (item) {
                        $dialogScope.importPaymentAmount = item.payment_amount;//引入的回款金额
                        $dialogScope.refundInfo = angular.extend(angular.copy(item), {contract_id: $data});
                        $dialogScope.refundInfo.payment_amount = myMath.sub($dialogScope.refundInfo.payment_amount, $dialogScope.refundInfo.have_payment_amount);
                        $dialogScope.refundInfo.input_date = $dialogScope.refundInfo.payment_date;
                    } else {
                        util.alert('请选择回款记录');
                        return false
                    }
                };

                $dialogScope.contractBaseInfo = {contract_id: $data};
                //新建回款
                $dialogScope.refundInfo = {
                    contract_id: $data
                };

                //实收金额变更时，重新计算分摊金额
                $dialogScope.$watch('refundInfo.payment_amount', function () {
                    $dialogScope.shareAmount();
                });

                //分摊回款金额
                $dialogScope.shareAmount = function () {
                    var items = $dialogScope.editInvoicePayments || [];
                    var refundAmount = ($dialogScope.refundInfo.payment_amount || 0);
                    $.each(items, function (i, d) {
                        if (!d._checked || refundAmount <= 0) {
                            d.cur_payment_amount = 0;
                            return true;
                        }
                        d.cur_payment_amount = myMath.sub(d.cur_billing_amount, d.total_payment);
                        refundAmount -= d.cur_payment_amount;
                        if (refundAmount < 0) {
                            d.cur_payment_amount += refundAmount;
                        }
                    });
                };

                $dialogScope.orgianlRefund = oldRefund;
                $dialogScope.refundType = refundType;

                //下拉框设置

                //获取应收信息列表
                if (refundType == 1) {
                    //非查看模式取发票信息
                    contractCommonService.getInvoiceReceivableInfoByContract($data, function (json) {
                        $dialogScope.editInvoicePayments = json;
                        $dialogScope.$applyAsync();
                    });
                }
            },
            onRefundImportNoInvoiceShow: function ($dialogScope, importType, dialog) {
                /**
                 * 引入未开票回款界面初始化
                 */
                $dialogScope.importPayments = [];
                $dialogScope.isloading = true;
                if (importType == 1) {
                    $dialogScope.importType = 1;//引入未开票回款
                    contractCommonService.getContractPaymentHaveAmountByContract($dialogScope.data.contract_id, function (data) {
                        $dialogScope.importPayments = data;
                        $dialogScope.isloading = false;
                        $dialogScope.$applyAsync();

                        setTimeout(function () {
                            dialog.reset();
                        }, 0);
                    })
                } else {
                    $dialogScope.importType = 2;//引入待录入回款
                    contractCommonService.getAccountHkList('', function (data) {
                        $dialogScope.importPayments = data;
                        $dialogScope.isloading = false;
                        $dialogScope.$applyAsync();

                        setTimeout(function () {
                            dialog.reset();
                        }, 0);
                    }, function () {
                        $dialogScope.isloading = false;
                        $dialogScope.$applyAsync();
                    });
                    $dialogScope.search = function (key) {
                        $dialogScope.isloading = true;
                        contractCommonService.getAccountHkList(key, function (data) {
                            $dialogScope.importPayments = data;
                            $dialogScope.isloading = false;
                            $dialogScope.$applyAsync();
                        }, function () {
                            $dialogScope.isloading = false;
                            $dialogScope.$applyAsync();
                        });
                    }
                }

                $dialogScope.selectPayment = function (item) {
                    $dialogScope.selectedItem = item;
                };
            },
            editRefundSave: function ($data, $dialog, $dialogScope, callback, contract) {
                /**
                 * 编辑回款
                 */
                function edit(){
                    var checkedInvoices = $.grep($dialogScope.editInvoicePayments || [], function (d, i) {
                        return d._checked == true;
                    });
                    if(checkedInvoices.length <= 0){
                        util.alert('请至少勾选一张发票信息');
                        return false;
                    }
                    $dialogScope.info.invoicePayments = checkedInvoices;
                    service.confirmRefundSave( $dialogScope.info, $dialog, callback, {
                        isEdit: true,
                        paymentId: $dialogScope.data.paymentId
                    });
                }

                //编辑款项归档时间
                function editInputDate(){
                  var info = $dialogScope.info;
                  service.confirmRefundSave(info,$dialog,callback);
                }

                if( $dialogScope.data.edit ){
                    var checkedInvoices = $.grep($dialogScope.editInvoicePayments || [], function (d, i) {
                        return d._checked == true;
                    });
                    if(checkedInvoices.length > 0){
                        return edit();
                    }else{
                        return editInputDate();
                    }
                }

                /**
                 * 保存新增回款
                 */
                var refundInfo = $dialogScope.refundInfo;
                //校验
                if (!refundInfo.finance_code) {
                    util.alert('请先引入回款');
                    return false;
                }
                //实收金额必须小于等于回款金额
                if (refundInfo.payment_amount > myMath.sub($dialogScope.importPaymentAmount, $dialogScope.refundInfo.have_payment_amount)) {
                    util.alert('实收金额不能大于未回款金额(' + myMath.sub($dialogScope.importPaymentAmount, $dialogScope.refundInfo.have_payment_amount) + ')');
                    return false;
                }
                if ($dialogScope.importType == 1) {
                    //如果是引入未开票回款，则恢复回款金额
                    refundInfo.payment_amount = $dialogScope.importPaymentAmount;
                }
                var checkedInvoices = $.grep($dialogScope.editInvoicePayments || [], function (d, i) {
                    return d._checked == true;
                })

                //校验
                if ($('.error:visible').length) {
                    return false;
                }

                refundInfo.invoicePayments = checkedInvoices;

                if(checkedInvoices.length <= 0){
                    util.alert('请至少勾选一张发票信息');
                    return false;
                }else{

                   if(checkedInvoices[0].customer_name != refundInfo.payment_account_name){
                       util.confirm('付款账号名称不等于已勾选发票的客户名称,是否继续?',{
                           ok:function(){service.confirmRefundSave(refundInfo,$dialog,callback); }
                       });
                    return false;
                   }else{
                       service.confirmRefundSave(refundInfo,$dialog,callback);
                   }

                }

                return false;
            },
            confirmRefundSave: function(post_data,$dialog,callback, options ){
                var url;
                if( options && options.isEdit ){
                    url = api_prefix + '/receivable/bind-contract-payment-to-invoice';
                    post_data.payment_id = options.paymentId;
                }else{
                    url = api_prefix + "/receivable/save-contract-payment";
                }
                util.myAjax({
                    url: url,
                    type: "POST",
                    context: this,
                    data: post_data,
                    async: false,
                    success: function (json) {
                        if (json.retCode == 0) {
                            util.alert("保存成功");
                            if (callback) {
                                callback();
                            }
                            $dialog.close();
                        } else {
                            util.alert("保存失败：" + json.errMsg);
                            return false;
                        }
                    }
                });
            },
            deleteRefund: function (refundInfo, callback) {
                /**
                 * 删除回款
                 */
                util.confirm('确定要删除此回款吗?', {
                    ok: function () {
                        var post_data = {payment_id: refundInfo.payment_id};
                        var url;
                        url = api_prefix + "/receivable/delete-contract-payment";

                        util.myAjax({
                            url: url,
                            type: "POST",
                            context: this,
                            data: post_data,
                            success: function (json) {
                                if (json.retCode == 0) {
                                    refundInfo.__isdelete = 1;
                                    util.alert("删除成功");
                                    $rootScope.$applyAsync();
                                    if (callback) {
                                        callback();
                                    }
                                } else {
                                    util.alert("删除失败：" + json.errMsg);
                                }
                            }
                        });
                    }
                });
            }
        };

        return service;
    }]);

    module.exports = ContractReceivableRefund;
});
